#include "Grid.h"
#include "Player.h"

VBO* GetGridVBO(vec3 min = vec3(), vec3 max = vec3())
{
	static VBO *vbo = NULL;

	if(!vbo)
	{
		vbo = new VBO;
	}

	return vbo;
}

Grid::Grid(vec3 pos, vec3 size)
{
	this->wPos = pos;
	this->max(size/2);
	this->min(-size/2);

	min.y = -(float)Max_Y_Bound;
	max.y = (float)Max_Y_Bound;
	color(1,1,1); alpha = 0.5f;
	detail_level = HIGH;

	id2 = vbo.Begin(GL_QUADS);
		vbo.AddVertex(min.x, GridHeight, min.z);
		vbo.AddVertex(min.x, GridHeight, max.z);
		vbo.AddVertex(max.x, GridHeight, max.z);
		vbo.AddVertex(max.x, GridHeight, min.z);
		vbo.SetColor(id2, color.x, color.y, color.z, alpha);
	vbo.End(GL_STREAM_DRAW);
}

// Check if Node is in this Grid
bool Grid::isNodeInGrid(Node *b)
{
	assert(b != NULL);

	if( BSphere *sphere = dynamic_cast<BSphere*>(b) )
	{
		return this->bIntersectsSphere(*sphere);
	}
	else if( BBox *box = dynamic_cast<BBox*>(b) )
	{
		return this->bIntersectsBox(*box);
	}
	else return false;
}

void Grid::Update(float delta)
{
	if( isNodeInGrid(player) )
	{
		alpha = 0.0f;
	}
	else
	{
		alpha = 0.5f;
		float distance = vec3(wPos.x, 0, wPos.z).distancesquared( player->wPos );
		if(distance < sqr(max.x * NearDistance))
		{
			color = NearColor;
			detail_level = HIGH;
		}
		else if(distance < sqr(max.x * MediumDistance))
		{
			color = MediumColor;
			detail_level = MEDIUM;
		}
		else
		{
			color = FarColor;
			detail_level = LOW;
		}
	}
}

void Grid::Draw(void)
{
	if(!bDraw) return;

	vbo.UpdateBegin(id2);
		vbo.AddVertex(min.x, GridHeight, min.z);
		vbo.AddVertex(min.x, GridHeight, max.z);
		vbo.AddVertex(max.x, GridHeight, max.z);
		vbo.AddVertex(max.x, GridHeight, min.z);
		vbo.SetColor(id2, color.x, color.y, color.z, alpha);
	vbo.UpdateEnd(id2);

	vbo.Draw();
}